package com.example.ordersservice.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.commonutils.JwtUtils;
import com.example.commonutils.R;
import com.example.commonutils.handler.NoqueueException;
import com.example.ordersservice.entity.OrderOrders;
import com.example.ordersservice.entity.VO.OrderSelectByConditionVO;
import com.example.ordersservice.service.OrderOrdersService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;


/**
 * <p>
 *  前端控制器:后台查询的控制器
 * </p>
 *
 * @author ${author}
 * @since 2023-06-23
 */
@RestController
@RequestMapping("/ordersservice/ordermanage")
public class OrderOrdersController {
    @Autowired
    private OrderOrdersService orderOrdersService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    //带条件的分页查询(根据下单用户的姓名、手机号、订单流水号、订单状态、时间范围等多条件进行查询)
    //分页插件
    @PostMapping("/selectPageByCondition/{page}/{pageSize}")
    public R selectPageByCondition(@RequestBody OrderSelectByConditionVO orderSelectByConditionVO,
                                   @PathVariable int page, @PathVariable int pageSize){
        LambdaQueryWrapper<OrderOrders> queryWrapper = new LambdaQueryWrapper<>();
        String ordersNumber = orderSelectByConditionVO.getOrdersNumber();
        String ordersName = orderSelectByConditionVO.getOrdersName();
        String ordersPhone = orderSelectByConditionVO.getOrdersPhone();
        Integer ordersStatus = orderSelectByConditionVO.getOrdersStatus();
        String begin = orderSelectByConditionVO.getBegin();
        String end = orderSelectByConditionVO.getEnd();
        queryWrapper.like(null != ordersName,OrderOrders::getOrdersName,ordersName);
        queryWrapper.eq(null != ordersNumber,OrderOrders::getOrdersNumber,ordersNumber);
        queryWrapper.eq(null != ordersPhone,OrderOrders::getOrdersPhone,ordersPhone);
        queryWrapper.eq(null != ordersStatus,OrderOrders::getOrdersStatus,ordersStatus);
        //无论有没有查询条件，状态为3的都不查询
        queryWrapper.ne(OrderOrders::getOrdersStatus,3);
        queryWrapper.ge(null != begin,OrderOrders::getGmtCreate,begin);
        queryWrapper.le(null != end,OrderOrders::getGmtCreate,end);
        queryWrapper.orderByDesc(OrderOrders::getGmtCreate);
        Page<OrderOrders> pageInfo = new Page<>(page,pageSize);
        orderOrdersService.page(pageInfo,queryWrapper);
        return R.ok().data("pageInfo",pageInfo);
    }
    //删除
    @DeleteMapping("/deleteOrders")
    public R deleteOrders(@RequestParam List<String> ids, HttpServletRequest request){
        String customerId = JwtUtils.getMemberIdByJwtToken(request);
        if (ids.size()==0){
            return R.error().message("请选中需要删除的订单");
        }
        //1.删除订单后同时删除订单详情表对应的数据
        orderOrdersService.batchDelete(ids);
        //2.删除成功后，清空缓存
        stringRedisTemplate.delete("cache:ordersAmount:"+customerId);
        Set<String> keys = stringRedisTemplate.keys("cache:orders:" + customerId + "*");
        stringRedisTemplate.delete(keys);
        return R.ok().message("删除成功");
    }
    //接单、派单
    @PostMapping("/accept/{id}")
    public R accept(@PathVariable String id) throws InterruptedException {
        LambdaQueryWrapper<OrderOrders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderOrders::getId,id);
        OrderOrders orders = orderOrdersService.getOne(queryWrapper);
        Integer ordersStatus = orders.getOrdersStatus();
        if (ordersStatus == 4){
            throw new NoqueueException(20001,"订单异常，请联系顾客退款");
        }
        if (ordersStatus == 2){
            throw new NoqueueException(20001,"您无需重复派单");
        }
        else if(ordersStatus == 0){
            orders.setOrdersStatus(1);
            orderOrdersService.updateById(orders);
            stringRedisTemplate.delete("cache:ordersAmount");
            //过一分钟后再执行，否则return超时
            Timer timer = new Timer();
            TimerTask task = new TimerTask() {
                @SneakyThrows
                @Override
                public void run() {
                    orderOrdersService.countDown(orders.getOrdersNumber());
                }
            };
            timer.schedule(task,1000*60);
            return R.ok().message("接单成功");
        }else{
            orders.setOrdersStatus(2);
            //手动派单成功后，将预计等待时间设置为0
            orders.setOrdersTime(0);
            orderOrdersService.updateById(orders);
            stringRedisTemplate.delete("cache:ordersAmount");
            return R.ok().message("派单成功");
        }
    }
    //查询某一天的总交易额
    @GetMapping("/getTotalPayAmount/{date}")
    public BigDecimal getTotalPayAmount(@PathVariable String date){
        return orderOrdersService.getTotalPayAmount(date);
    }
    //查询某一天的总订单数
    @GetMapping("/getTotalNum/{date}")
    public int getTotalNum(@PathVariable String date){
        return orderOrdersService.getTotalNum(date);
    }
}

